package org.gtesoreria

import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.compass.core.engine.SearchEngineQueryParseException
import org.gtesoreria.utils.MenuOption;

class AfiliadoController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    
    def delegados() {return Afiliado.findAllNotEsDelegado() }
    
    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 30, 100)
        [afiliadoInstanceList: Afiliado.list(params), afiliadoInstanceTotal: Afiliado.count(), breadcrumbOptions:["Afiliados","Buscar"]]
    }

    def create = {
        def afiliadoInstance = new Afiliado()
        afiliadoInstance.properties = params
        return [afiliadoInstance: afiliadoInstance]
    }

    def save = {
        def afiliadoInstance = new Afiliado(params)
        if(afiliadoInstance.esDelegado){
			afiliadoInstance.delegado = null
		}
        def _toBeRemoved = afiliadoInstance.familiars.findAll {!it}

        // if there are familiars to be removed
        if (_toBeRemoved) {
			afiliadoInstance.familiars.removeAll(_toBeRemoved)
         }
		
        //update my indexes
        afiliadoInstance.familiars.eachWithIndex(){dpn, i ->
			if(dpn)
				dpn.index = i
        }
        afiliadoInstance.setMesNacimiento(null);
        if (afiliadoInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'afiliado.label', default: 'Afiliado'), afiliadoInstance.id])}"
            redirect(action: "show", id: afiliadoInstance.id)
        }
        else {
            render(view: "create", model: [afiliadoInstance: afiliadoInstance])
        }
    }

    def show = {
        def afiliadoInstance = Afiliado.get(params.id)
        if (!afiliadoInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'afiliado.label', default: 'Afiliado'), params.id])}"
            redirect(action: "list")
        }
        else {
			def afiliadosOptions = [new MenuOption(link:"/GTesoreria/afiliado/show/" + params.id, text:afiliadoInstance.apellidoNombre),
									new MenuOption(link:"/GTesoreria/adelanto/adelantos?afiliadoId=" + params.id, text:"Adelantos"),
									new MenuOption(link:"/GTesoreria/consumo/consumos?afiliadoId=" + params.id, text:"Consumos"),
									new MenuOption(link:"/GTesoreria/prestamo/prestamo?afiliadoId=" + params.id, text:"Prestamos")]
			def breadcrumbOptions = ["Afiliados", afiliadoInstance.apellidoNombre]
			[afiliadoInstance: afiliadoInstance,afiliadosOptions:afiliadosOptions, breadcrumbOptions:breadcrumbOptions]
        }
    }

    def edit = {
        def afiliadoInstance = Afiliado.get(params.id)
        if (!afiliadoInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'afiliado.label', default: 'Afiliado'), params.id])}"
            redirect(action: "list")
        }
        else {
			def afiliadosOptions = [new MenuOption(link:"/GTesoreria/afiliado/show/" + params.id, text:afiliadoInstance.apellidoNombre),
				new MenuOption(link:"/GTesoreria/adelanto/adelantos?afiliadoId=" + params.id, text:"Adelantos"),
				new MenuOption(link:"/GTesoreria/consumo/consumos?afiliadoId=" + params.id, text:"Consumos")]
			def breadcrumbOptions = ["Afiliados", afiliadoInstance.apellidoNombre]
            return [afiliadoInstance: afiliadoInstance,afiliadosOptions:afiliadosOptions, breadcrumbOptions:breadcrumbOptions]
        }
    }

    def update = {
        def afiliadoInstance = Afiliado.get(params.id)
        if (afiliadoInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (afiliadoInstance.version > version) {
                    
                    afiliadoInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'afiliado.label', default: 'Afiliado')] as Object[], "Another user has updated this Afiliado while you were editing")
                    render(view: "edit", model: [afiliadoInstance: afiliadoInstance])
                    return
                }
            }
            afiliadoInstance.properties = params
            
            // find the familiars that are marked for deletion
            def _toBeDeleted = afiliadoInstance.familiars.findAll {it?.deleted || !it}

            // if there are familiars to be deleted remove them all            
            if (_toBeDeleted) {
                afiliadoInstance.familiars.removeAll(_toBeDeleted)
            }
            
            //update my indexes
            afiliadoInstance.familiars.eachWithIndex(){dpn, i ->
				if(dpn)
					dpn.index = i
            }
			afiliadoInstance.setMesNacimiento(null);
            if (!afiliadoInstance.hasErrors() && afiliadoInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'afiliado.label', default: 'Afiliado'), afiliadoInstance.id])}"
                redirect(action: "show", id: afiliadoInstance.id)
            }
            else {
                render(view: "edit", model: [afiliadoInstance: afiliadoInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'afiliado.label', default: 'Afiliado'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def afiliadoInstance = Afiliado.get(params.id)
        if (afiliadoInstance) {
            try {
                afiliadoInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'afiliado.label', default: 'Afiliado'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'afiliado.label', default: 'Afiliado'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'afiliado.label', default: 'Afiliado'), params.id])}"
            redirect(action: "list")
        }
    }
	def importadorService;
	def upload = {
		CommonsMultipartFile f = request.getFile('myFile')
		if(!f.empty) {
			importadorService.importAfiliados f
		  redirect(action: "list")
		}
		else {
		   flash.message = 'file cannot be empty'
		   redirect(action: "list")
		}
	}
	
	def uploadFamiliars = {
		CommonsMultipartFile f = request.getFile('myFile')
		if(!f.empty) {
			importadorService.importFamiliares f
		  redirect(action: "list")
		}
		else {
		   flash.message = 'file cannot be empty'
		   redirect(action: "list")
		}
	}
	
	def home = {
		render(view:"afiliadoHome", model:[ breadcrumbOptions:["Afiliados"]]);
	}
	
	def searchableService
	def search = {
		if (!params.searchText?.trim() && !params.searchTextParam) {
			redirect(action: "home", controller:"afiliado")
		}
		try {
			String text = null;
			if(params.searchText)
				text = params.searchText.trim();
			if(params.searchTextParam)
				text =  params.searchTextParam.trim() 
			def resultado = searchableService.search("*" + text + "*",[max:params.max, offset:params.offset,order:params.order, sort:params.sort]);			
			def afiliados = resultado.results.collect{ val -> Afiliado.get(val.id) }
			def total = searchableService.countHits("*" + text + "*");
			render(view: "list", model:[afiliadoInstanceList: afiliados, afiliadoInstanceTotal: total, breadcrumbOptions:["Afiliados", "Buscar"],searchTextParam:text])
		} catch (SearchEngineQueryParseException ex) {
			return [parseException: true]
		}
	}
	
	
	
	def cancel = {

			}
}
